Python socket server 多线程 转发

Server:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import socket
import sys
from thread import *

HOST = '' # Symbolic name meaning all available interfaces
PORT = 5555 # Arbitrary non-privileged port
lock = 0
client = 0
data = None
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
#Bind socket to local host and port
try:
s.bind((HOST, PORT))
except socket.error , msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()

print 'Socket bind complete'

#Start listening on socket
s.listen(10)
print 'Socket now listening'

#Function for handling connections. This will be used to create threads
def clientthread(conn, client):
global data, lock
#Sending message to connected client
# conn.send('Welcome to the server. Type something and hit enter\n') #send only takes string

#infinite loop so that function do not terminate and thread do not end.
while True:

#Receiving from client
if client % 2 == 0:
data = conn.recv(1024)
reply = 'OK...' + data
lock = 1
if not data:
break

conn.sendall(reply)
else:
if lock == 1:
conn.sendall(data)
lock = 0


#came out of loop
conn.close()

#now keep talking with the client
while 1:

#wait to accept a connection - blocking call
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])

#start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.
start_new_thread(clientthread ,(conn,client,))
client += 1

s.close()

要点:开启多线程的时候多个线程用的代码段是相同的。要想不相同的可以加上lock、client标志进行判断!

Client one:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# -*- coding: utf-8 -*-
import socket

HOST='127.0.0.1'
PORT=5555

s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) #定义socket类型,网络通信,TCP
s.connect((HOST,PORT)) #要连接的IP与端口
while 1:
cmd=raw_input("Please input cmd:") #与人交互,输入命令
s.sendall(cmd) #把命令发送给对端
data=s.recv(1024) #把接收的数据定义为变量
print(data) #输出变量
s.close() #关闭连接

Client two :

1
2
3
4
5
6
7
8
9
10
11
12
# -*- coding: utf-8 -*-
import socket

HOST='127.0.0.1'
PORT=5555

s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) #定义socket类型,网络通信,TCP
s.connect((HOST,PORT)) #要连接的IP与端口
while 1:
data=s.recv(1024) #把接收的数据定义为变量
print(data) #输出变量
s.close() #关闭连接

注意要先连接第一个,再连接第二个。

------ 本文结束------
坚持原创技术分享,您的支持将鼓励我继续创作!

欢迎关注我的其它发布渠道